package light.im;

import java.io.IOException;
import java.nio.channels.CompletionHandler;
import light.network.EndpointSession;
import light.network.Packet;
import light.network.PackProtocal;
import light.network.object.PackObject;

public class UdpIMSession implements IMSession {

	EndpointSession endpointSession;
	//Packet dataBuffer = UdpPacket.allocate(1024*10-4);
	String userId;
	boolean isLogin;
	IMEndpoint imServer;
	
	int requestId = -1;
	
	public UdpIMSession(EndpointSession ioSession, IMEndpoint imServer)
	{
		this.endpointSession = ioSession;
	}
	
	@Override
	public void write(PackObject params)
	{
		if(requestId>-1)
			params.put(ActionDispather.RequestPackageKey, requestId);
		Packet dataBuffer = PackProtocal.unwrapUDP(params);
		try {
			endpointSession.send(dataBuffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getId()
	{
		return endpointSession.getId();
	}

	@Override
	public void write(PackObject params, Object attachment, CompletionHandler<Integer, Object> handler) throws IOException {

		if(requestId>-1)
			params.put(ActionDispather.RequestPackageKey, requestId);
		endpointSession.send(PackProtocal.unwrapUDP(params), attachment, handler);;
	}

	@Override
	public IMEndpoint getIMServer() {
		return imServer;
	}

	public IMSession requestId(int reqId)
	{
		requestId = reqId;
		return this;
	}
}
